package lambdasinaction.chap11.CountDownLatch;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        int numberOfThreads = 3;
        CountDownLatch latch = new CountDownLatch(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            new Thread(new work(latch)).start();
        }

        // Main thread waits until all workers have finished
        latch.await();
        System.out.println("All workers have finished. Main thread proceeds.");
    }
}

class work implements Runnable {
    private CountDownLatch latch;

    public work(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            System.out.println("Worker " + Thread.currentThread().getId() + " is working...");
            Thread.sleep(2000); // Simulate work
            System.out.println("Worker " + Thread.currentThread().getId() + " has finished.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown(); // Decrement the count of the latch
        }
    }
}
